'use strict';

app.controller('LoginController', ['$rootScope', '$scope', '$window', '$state', '$location', function ($rootScope, $scope, $window, $state, $location) {
    $scope.login = function () {
        $scope.auth = {};
        $scope.auth.msg = null;
        $scope.auth.buttonDisable = true;
        // Try to login
        $.post('j_spring_security_check', {
                username: $scope.username,
                password: $scope.password
            },
            function (data) {
                $scope.auth.buttonDisable = false;
                if (data.success) {
                    $rootScope.flushUserInfo().then(function(){
                        $scope.goTarget();
                    },function(){
                        $scope.goTarget();
                    });
                } else {
                    $scope.auth.msg = data.msg;
                    $rootScope.cacheUrlState = undefined;
                    $rootScope.needLogin = false;
                    $scope.$apply();
                }
            }, "json");
    };

    $scope.goTarget = function(){
        if ($rootScope.needLogin && angular.isDefined($rootScope.cacheUrlState) && angular.isDefined($rootScope.cacheUrlState.toState)) {
            var toState = $rootScope.cacheUrlState.toState;
            var toParams = $rootScope.cacheUrlState.toParams;
            $rootScope.needLogin = false;
            $state.go(toState.name, toParams, {reload : true, inherit:false});
        } else {
            $rootScope.needLogin = false;
            $state.go('app.home', {}, {reload : true});
        }
    }
}]);